<template>
  <div>
    <!--  顶部面包屑  -->
    <div class="ccui-navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回
      </el-button>
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}
        </el-breadcrumb-item>
        <el-breadcrumb-item
          :to="{ path: '/orderManagement/entry/un-submitted' }"
          >订单管理
        </el-breadcrumb-item>
        <el-breadcrumb-item
          :to="{
            path: '/orderManagement/entry/un-submitted'
          }"
          >订单录入
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="ccui-curr-crumb">新增订单</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs v-model="activeName" class="el-tabs__customize">
          <el-tab-pane label="基本信息" name="a">
            <basicInfo
              class="commonClass"
              ref="basicInfo"
              @postPconcId="getPconcId"
              @clearTable="clearTable"
              :thirdCategories="thirdCategories"
              @clear-table="clearTableData"
            ></basicInfo>
          </el-tab-pane>

          <el-tab-pane label="采购清单" name="b">
            <tableList
              class="commonClass"
              ref="tableList"
              :concId="concId"
              :clearTableList="clearTableList"
              @postTableData="getTableData"
            ></tableList>
          </el-tab-pane>

          <el-tab-pane label="附件" name="c">
            <attachment ref="attachment" class="commonClass"></attachment>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandleKeep()"
            >暂存
          </el-button>
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('save')"
            >保存并校验
          </el-button>
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('submit')"
            >保存并提交
          </el-button>
        </li>
        <div class="ccui-bottom-guide-divider" />
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回
          </el-button>
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import basicInfo from "@/app/orderManagement/orderEntry/components/basicInfo";
import tableList from "@/app/orderManagement/orderEntry/components/tableList";
import attachment from "@/app/orderManagement/components/attachment";
// import attachment from "@/basa/components/public/uploadInfo2";
import { saveOrder, enteringApproval, tempSaveOrder } from "../api/orderEntry";
import { ishasAgentId } from "@/basa/utils";

export default {
  name: "add",
  components: {
    basicInfo,
    tableList,
    attachment
  },
  inject: ["reload"],
  data() {
    return {
      activeName: "a",
      submitFlag: false, // 缓存
      concId: null,
      clearTableList: null,
      thirdCategories: {} // 分类名称
    };
  },
  methods: {
    // 清空采购清单方法
    clearTableData(data) {
      console.log("调用清空方法,data", data);
      console.log("调用清空方法,data", "22");
      this.$refs["tableList"].tableData = [];
      this.$refs["tableList"].copyData = [];
    },
    clearTable(params) {
      this.clearTableList = params;
    },
    getTableData(params) {
      this.thirdCategories = params;
    },
    getPconcId(params) {
      this.concId = params;
    },
    // 保存 / 提交
    submitHandle(type) {
      this.$refs["basicInfo"].$refs["basicInfo"].validate(valid => {
        if (valid) {
          // 基本信息 - 订单发出时间处理
          this.$refs["basicInfo"].orderDeliveryTime1 =
            this.$refs["basicInfo"].getTime();
          let times = this.$refs["basicInfo"].getTime();
          this.$refs["basicInfo"].form.orderDeliveryTime = new Date(
            times
          ).getTime();
          this.$refs["tableList"].tableData.forEach((item, index) => {
            item.sn = index;
            item.brandRelation = item.smpBrandRelationReqBOS;
            item.brandRelation.forEach(i => {
              i.contractBrandRelId = i.id;
              delete i.id;
            });
            // delete item.smpBrandRelationReqBOS;
          });
          // 处理表格附件入参
          let ocFilesBo = this.$refs.attachment.tableData.map((e, index) => {
            return {
              sn: index,
              uploadTime: Date.parse(e.uploadTime.replace(/-/g, "/")),
              uploadId: e.uploadId,
              fileDesc: e.fileDesc ? e.fileDesc : ""
            };
          });
          console.log("附件", ocFilesBo);
          let bool = this.$refs["basicInfo"].$refs["basicInfo"];
          bool.validate(valid => {
            if (valid) {
              type === "save"
                ? this.saveOrder(ocFilesBo)
                : this.enteringApproval(ocFilesBo);
            }
          });
        } else {
          this.activeName = "a";
          // this.$message({
          //   duration: 2000,
          //   message: "基本信息有未输入内容",
          //   type: "error",
          //   ccuiCustom: true
          // });
        }
      });
    },
    // 保存
    saveOrder(ocFilesBo) {
      let params = {
        ocOrderBasic: this.$refs["basicInfo"].form,
        ocOrderBills: this.$refs["tableList"].tableData,
        ocFilesBO: ocFilesBo,
        isShowPageLoading: true,
        loadingMessage: "保存中,请稍等..."
      };
      saveOrder(params)
        .then(res => {
          let { code, message } = res.data;
          if (code === "0") {
            this.$message.success(message);
          } else {
            this.$showErrorMessage(message);
          }
          this.submitFlag = true;
          this.handleBack();
        })
        .catch(e => {
          if (e.data.code === "105") {
            this.activeName = "b";
          }
        });
    },
    // 提交
    enteringApproval(ocFilesBo) {
      let params = {
        ocOrderBasic: this.$refs["basicInfo"].form,
        ocOrderBills: this.$refs["tableList"].tableData,
        ocFilesBO: ocFilesBo,
        isShowPageLoading: true,
        loadingMessage: "保存中,请稍等..."
      };
      enteringApproval(params)
        .then(res => {
          let { code, message } = res.data;
          if (code === "0") {
            this.$message.success(message);
          } else {
            this.$showErrorMessage(message);
          }
          this.submitFlag = true;
          this.handleBack();
        })
        .catch(e => {
          if (e.data.code === "105") {
            this.activeName = "b";
          }
        });
    },
    // 暂存
    submitHandleKeep() {
      if (this.$refs["tableList"].tableData) {
        this.$refs["tableList"].tableData.forEach((item, index) => {
          item.sn = index;
          if (item.smpBrandRelationReqBOS) {
            item.brandRelation = item.smpBrandRelationReqBOS;
          }
          item.brandRelation.forEach(i => {
            if (i.id) {
              i.contractBrandRelId = i.id;
              delete i.id;
            }
          });
          // delete item.smpBrandRelationReqBOS;
        });
      }
      let ocFilesBo = this.$refs.attachment.tableData.map((e, index) => {
        return {
          sn: index,
          uploadTime: Date.parse(e.uploadTime.replace(/-/g, "/")),
          uploadId: e.uploadId,
          fileDesc: e.fileDesc ? e.fileDesc : ""
        };
      });
      console.log(ocFilesBo, "dfdfdfddfdfdf");
      let params = {
        ocOrderBasic: this.$refs["basicInfo"].form,
        ocOrderBills: this.$refs["tableList"].tableData,
        ocFilesBO: ocFilesBo,
        isShowPageLoading: true,
        loadingMessage: "保存中,请稍等..."
      };
      tempSaveOrder(params)
        .then(res => {
          console.log(res);
          this.handleBack();
          let { code, message } = res.data;
          if (code === "0") {
            this.$message.success(message);
          } else {
            this.$showErrorMessage(message);
          }
        })
        .catch(e => {
          console.log(e);
        });
    },
    // 返回按钮
    handleBack() {
      this.$router.push(
        sessionStorage.getItem("fromPath") ||
          "/orderManagement/entry/un-submitted"
      );
      this.reload();
    }
  },
  beforeRouteEnter(to, from, next) {
    !(to.fullPath === from.fullPath) &&
      sessionStorage.setItem("fromPath", from.fullPath);
    next();
  },
  // 更改列表缓存状态
  beforeRouteLeave(to, from, next) {
    this.reload();
    if (this.submitFlag === true) {
      for (var key in this.$vnode.parent.parent.componentInstance.cache) {
        delete this.$vnode.parent.parent.componentInstance.cache[
          ishasAgentId(to.path, key)
        ];
      }
    }
    next();
  }
};
</script>

<style scoped lang="scss">
.commonClass {
  margin-top: 5px;
}

/deep/ .el-group-title .group-content {
  margin-top: 40px;
}
/deep/ .el-group-title.ccui-group-wrapper .extend-btn {
  position: absolute;
  top: 0px;
  right: 0;
}
</style>
